<script setup lang="ts">
import MaterialSettingModal from '../../dialog/MaterialSetting/index.vue';
import useEmit from '@/hooks/useEmitter';
import usePageSave from '@/hooks/usePageSave';
import procurementUnit from '@/views/Base/MaterialsManagement/dialog/procurementUnit/index.vue';
import { checkRepeat, RepeatMsg } from '@/utils';
import { tableConfig } from './config/table-config';
import { Message } from '@/instance';
import { doGetMaterialSetting, doAddMaterial } from '@/api/base/materialsManagement';
import type { MaterialListInfo, MaterialSetting } from '@/api/base/materialsManagement/model/type';
import { filterByKey } from '@/utils';
defineOptions({
    name: 'MaterialsManagementAdd'
});

const { loading, modalOk, modalSlotRef: tableRef } = useModal();

const STORE_KEY = 'materialsManagementAddData'; // store数据的key
const { startRecording, isUpdate } = useEmit(STORE_KEY); // 页面标签路由关闭二次确认事件监听

useRecordData(tableRef, STORE_KEY, isUpdate, startRecording); // 复制物料相关

const materialSettingList = ref<StandardOptions[]>([]);

const getMaterialList = async () => {
    try {
        const res = await doGetMaterialSetting(false);

        if (res.data && res.data.records)
            materialSettingList.value = res.data.records.map((item: MaterialSetting) => ({
                value: item.id!,
                label: item.classificationName!
            }));
    } catch (error) {
        console.error(error);
    }
};

/**
 * 保存新增数据
 */
const addData = async () => {
    try {
        let data: MaterialListInfo[] = tableRef.value.getSaveData();
        let tableData = tableRef.value.tableData;
        data = data.map((item, index) => {
            return { ...item, materialUnitId: tableData[index].processId };
        });
        const msg = checkRepeat(data, ['materialCode']);
        if (msg) {
            const { value, line } = msg;
            RepeatMsg({ value, line, label: '物料编码' });
            return;
        }

        const res = await doAddMaterial(data);
        Message.success('操作成功！');
        return res;
    } catch (error) {
        console.error(error);
    }
};

/**
 * 点击保存按钮
 */
const handleOk = async () => {
    try {
        await modalOk(addData);
        usePageSave('/materialsManagement');
    } catch (e) {
        console.log(e);
    }
};

/**
 * 跳转至物料分类设置
 */
const selectRef = ref();
const materialSettingRef = ref();
const toMarerialSetting = () => {
    // 数据更改后再做逻辑操作，防止页面闪烁问题
    nextTick(() => {
        selectRef.value.blur();
        materialSettingRef.value.handleDialog(); // 打开物料分类设置;
    });
};

/**
 * 点击生产单位
 */
const selectProcedureId = ref(); // 记录当前选项 id 用于数据填充
const validProcedureId = ref(); // 记录当前校验 id 用于清除表格验证
const validIndex = ref(0); // 校验列表索引
const procedureId = ref(); //选中的数据id
const productUnit = ref(); // 生产单位
const procedureCodeVisible = ref(false);
const handleClickProcedureCode = (row: anyObj, id: number | string, index: number) => {
    selectProcedureId.value = row.id;
    validProcedureId.value = id;
    validIndex.value = index;
    procedureId.value = row.productUnit ? row.processId : ''; // 防止清空生产单位，数据回显 bug
    productUnit.value = row.productUnit;
    procedureCodeVisible.value = true;
};
/**
 * 选择生产单位点击保存
 */
const handleProcedureCodeOk = (productUnits: MaterialSetting) => {
    if (!productUnits || !Object.keys(productUnits).length) return;
    // resetRelatedValid([validProcedureId.value], validIndex.value); // 清除选项校验

    // 过滤出当前所选的 id 项
    const currentOption = filterByKey(tableRef.value.tableData, selectProcedureId.value);
    if (currentOption) {
        for (let key in productUnits) {
            if (key === 'id') {
                currentOption['processId'] = productUnits[key];
                continue;
            }
            //赋值给新增数据列表的生产单位和采购单位,并且清空上一次的选择
            if (!productUnits.productUnit) currentOption['productUnit'] = '';
            if (!productUnits.purchaseUnit) currentOption['purchaseUnit'] = '';
            if (!productUnits.productPurchaseUnitRatio)
                currentOption['productPurchaseUnitRatio'] = '';
            currentOption[key] = productUnits[key];
        }
    }
};
onActivated(() => {
    getMaterialList();
});

//路由信息
const router = useRouter();

const handleCancel = () => {
    router.push('/materialsManagement');
};
</script>

<template>
    <q-page>
        <base-table
            ref="tableRef"
            :add-table-row="true"
            :open-sticky="true"
            :show-fullscreen="true"
            :tableConfig="tableConfig"
        >
            <!-- 保存/取消 -->
            <template #tableHeadEnd>
                <q-submit-button
                    size="default"
                    :hide-label="true"
                    align="right"
                    :horizontal="true"
                    :loading="loading"
                    @save="handleOk"
                    @cancel="handleCancel"
                />
            </template>
            <template #materialClassificationSlot="{ row, item, validFn }">
                <el-select
                    ref="selectRef"
                    v-model="row[item.modelKey!]"
                    placeholder="请选择"
                    clearable
                    popper-class="push-select"
                    @focus="
                        (e: any) =>
                            validFn.handleFocus(e, row, {
                                config: item
                            })
                    "
                    @change="validFn.setValidErrorVisible(false)"
                    @blur="validFn.setValidErrorVisible(false)"
                >
                    <el-option
                        v-for="item in materialSettingList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                    <template #footer>
                        <q-push-button
                            @click="
                                row[item.modelKey!] = '';
                                toMarerialSetting();
                            "
                        />
                    </template>
                </el-select>
            </template>
            <template #productUnit="{ row, item, index }">
                <q-virtual-select
                    v-model="row.productUnit"
                    :closable="true"
                    placeholder="请选择"
                    @click="handleClickProcedureCode(row, item.validProps?.id!, index)"
                />
            </template>
            <template #purchaseUnit="{ row }">
                {{ row.purchaseUnit || '--' }}
            </template>
        </base-table>

        <!-- 物料分类设置 -->
        <MaterialSettingModal ref="materialSettingRef" />
        <!-- 采购单位 -->
        <procurementUnit
            :id="procedureId"
            v-model:visible="procedureCodeVisible"
            :productUnit="productUnit"
            @ok="handleProcedureCodeOk"
        />
    </q-page>
</template>

<style lang="scss" scoped></style>
